var http = require('http');
var fs = require('fs');
var url = require('url');
var querystring = require('querystring');
var port = 80; 
var ip = "127.0.0.1"
var util = require('util')
var title = 'D.blog.xiang'
var server = http.createServer(function (request, response) {
	response.statusCode = 200;
	var ext =request.url.substr( request.url.lastIndexOf(".")+1)
	var exts = {
		'html' : "text/html",
		'css' :' text/css',
		'jpg':'image/jpeg',
		'js':"application/x-javascript"
	}
	if (exts[ext] == null) {
		exts[ext] = "text/plain"
	}
	response.setHeader('Content-Type',exts[ext])
	var p = url.parse(request.url,true)
	var data = ""
	if (request.url == '/about.html') {
			try{
				data = fs.readFileSync("."+request.url,'utf8')
				data = data.replace(/%title/g,title)
				item = fs.readFileSync('data.json','utf8')
				item = JSON.parse(item)
				var s = ''
				for (var i = 0; i < item.length; i++) {
					s+= '<div class="con">'
					s+=	'<h6>'+item[i].author+'<span>'+item[i].time+'</span></h6>'
					s+=	'<p>'+item[i].message+'<a href="/delmessage">删除</a></p>'
					s+=	'</div>'
				}	
			}
			catch(e){
		}
		data = data.replace(/%main/g,s)
		response.write(data)
		response.end()
	}else if (request.url == '/form.html') {
		data = fs.readFileSync("."+request.url,'utf8')
	response.write(data)
	response.end()
		}else if (p.pathname =="/addmessage") {
			var s = ''
			request.on('data', function(data){    
				s+= data;
        });
			request.on('end', function(){
			s = querystring.parse(s)
			item = fs.readFileSync('data.json','utf8')
			item = JSON.parse(item)
			item.push({
					author:s.author,
					message:s.message,
					time:new Date()                
				})
			item = fs.writeFileSync('data.json',JSON.stringify(item))
			response.writeHead(302,{
				'location':'/about.html'
			})
	response.end()
		});
    }else if (p.pathname =="/delmessage") {
			item = fs.readFileSync('data.json','utf8')
			item = JSON.parse(item)
			id = p.query.id;
			item.splice(id,1)
			item = JSON.stringify(item)
			item = fs.writeFileSync('data.json',item)
			response.writeHead(302,{
				'location':'/about.html'
			})
	response.write(data)
	response.end()
		}
})
server.listen(port);
console.log('Server running at http://%s:%s/',ip,port);